
function [DSd,DB]=DB_vg(Pt,BB,DBB,nm,AA,Z,ZZ,v,ep_sd,n)

N=length(BB)/2;

R=exp(-ZZ);
V=diag(v.*ep_sd);
Q=V*R*V;
P0I=kron(eye(2),tril(Q)+tril(Q,-1)');

if n>0
    DV=diag([zeros(n-1,1);ep_sd(n,1);zeros(N-n,1)]);
    DP0I=kron(eye(2),V*R*DV+(V*R*DV)');
    DP0I=P0I\(DP0I/P0I);
else
    DR=-Z.*R;
    DP0I=kron(eye(2),V*DR*V);
    DP0I=P0I\(DP0I/P0I);
end

DSd=0.5*diag(Pt\eye(2*N)).^(-1/2).*diag(Pt\(DP0I/Pt));

DB=DBB;
DB([nm;N+nm],1)=AA([nm;N+nm],[nm;N+nm])*DBB([nm;N+nm],1)+Pt([nm;N+nm],[nm;N+nm])\(DP0I([nm;N+nm],[nm;N+nm])*BB([nm;N+nm],1));
